package org.jgs1904.bean;

import lombok.Data;

import java.util.List;

/**
 * 分页实体类
 *
 * @author junki
 * @date 2020年3月31日
 */
@Data
public class Pager<E> {

    /**
     * 当前页
     */
    private Long currentPage;

    /**
     * 每页显示数据量
     */
    private Long pageSize;

    /**
     * 数据表中总数据量
     */
    private Long totalRows;

    /**
     * 页面显示页码总量
     */
    private Long pageNumShowLength;

    /**
     * 总页数  totalRows / pageSize
     */
    private Long totalPages;

    /**
     * 数据库分页开始的索引  (currentPage - 1) * pageSize
     */
    private Long startIndex;

    /**
     * 页面显示的开始页码
     */
    private Long startPage;

    /**
     * 页面显示的结束页码
     */
    private Long endPage;

    /**
     * 数据集合
     */
    private List<E> dataList;


    public Pager(Long currentPage, Long pageSize, Long totalRows, Long pageNumShowLength) {
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.totalRows = totalRows;

        // 计算总页数
        if (this.totalRows % this.pageSize == 0) {
            this.totalPages = this.totalRows / this.pageSize;
        } else {
            this.totalPages = this.totalRows / this.pageSize + 1;
        }

        // 判断currentPage合法性
        if (this.currentPage > this.totalPages) {
            this.currentPage = this.totalPages;
        }

        // 计算数据库分页开始索引
        this.startIndex = (this.currentPage - 1) * this.pageSize;
        if (this.startIndex < 0) {
            this.startIndex = 0L;
        }

        // 计算页面显示起始页码和结束页码
        if (this.totalPages <= pageNumShowLength) {
            this.startPage = 1L;
            this.endPage = this.totalPages;
        } else if (this.currentPage <= (pageNumShowLength / 2 + 1)) {
            this.startPage = 1L;
            if (this.totalPages <= pageNumShowLength) {
                this.endPage = this.totalPages;
            } else {
                this.endPage = pageNumShowLength;
            }
        } else {
            if (pageNumShowLength % 2 == 0) {
                if (this.totalPages <= (this.currentPage + (pageNumShowLength / 2) - 1)) {
                    this.startPage = this.totalPages - pageNumShowLength + 1;
                    this.endPage = this.totalPages;
                } else {
                    this.startPage = this.currentPage - (pageNumShowLength / 2);
                    this.endPage = this.currentPage + (pageNumShowLength / 2) - 1;
                }
            } else {
                if (this.totalPages <= (this.currentPage + (pageNumShowLength / 2))) {
                    this.startPage = this.totalPages - pageNumShowLength + 1;
                    this.endPage = this.totalPages;
                } else {
                    this.startPage = this.currentPage - (pageNumShowLength / 2);
                    this.endPage = this.currentPage + (pageNumShowLength / 2);
                }
            }
        }

    }

}
